package com.lanou3g.code0423;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * Created by dllo on 18/4/23.
 */
public class SendClient {   //直接运行发送方,就是所谓的丢包
    public static void main(String[] args) {

        try{
            //暂时不需要接收数据,所以随机绑定一个端口号即可
            DatagramSocket ds = new DatagramSocket();

            String s = "Hello world";
            byte[] buf = s.getBytes(); //获取字符数组

            //new InetSocketAddress("127.0.0.1",7788) 是要发送的目的地 地址和端口号
            //255.255.255.255 是广播地址,会向这个局域网网段的所有7788端口发送数据,所有的都能收到message
            DatagramPacket dp = new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",7788));
            System.out.println(buf.length);
            ds.send(dp);  //发送


            //等待接收(接收方地址没有手动指定)
            byte[] bytes = new byte[1024];
            DatagramPacket  packet = new DatagramPacket(bytes,bytes.length);
            ds.receive(packet);//等着接收数据
            String data = new String(packet.getData(),0,packet.getLength());
            System.out.println(data);
            System.out.println(packet.getAddress());
            System.out.println(packet.getPort());

            ds.close();
        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
